package com.sunsharing.sysdb;

import com.alibaba.druid.pool.DruidDataSource;
import com.sunsharing.entity.DbInit;
import com.sunsharing.entity.DbSource;
import com.sunsharing.utils.XmlUtil;
import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@Log4j
public class DynamicDataSource {

    private static final Map<String, JdbcTemplate> dataSourceList = new HashMap<>();
    public static DbInit dbInit = null;
    private String localPath = System.getProperty("user.dir") + "\\conf\\conf.xml";//当前路径

    public DynamicDataSource() throws
            ClassNotFoundException,
            NoSuchFieldException,
            InstantiationException,
            IllegalAccessException,
            InvocationTargetException {

        //读取配置文件
        XmlUtil xmlUtil = new XmlUtil();
        dbInit = xmlUtil.parse2Object(localPath, DbInit.class);
        loadDataSource();

    }


    // 加载数据源
    private void loadDataSource() {
        List<DbSource> dbSources = dbInit.getDataSources();
        for (DbSource config : dbSources) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(config.getUrl());
            dataSource.setUsername(config.getUsername());
            dataSource.setUsername(config.getUsername());
            dataSource.setPassword(config.getPassword());
            dataSource.setDriverClassName(config.getDriver());
            dataSourceList.put(config.getName(), new JdbcTemplate(dataSource));
        }
    }

    public static JdbcTemplate getTemplate(String sourceName) {
        JdbcTemplate jdbcTemplate = dataSourceList.get(sourceName);
        if (jdbcTemplate == null) {
            log.info("对不起：找不到【" + sourceName + "】对应的数据源，请查看" + System.getProperty("user.dir") + "\\conf\\conf.xml配置文件是否配置完整！！");
            throw new RuntimeException();
        }
        return jdbcTemplate;
    }
}
